import urllib2,urllib
from xml.dom.minidom import parse, parseString
import socket
from wowhead.exceptions import ItemNotFountException, WowHeadConectionProblem, ItemNotParseable

class Request():
	"""Plain Request to wowhead api"""
	
	def __init__(self,language):
		self.language = language
		self.userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4"
		self.item_id = 0
		self.tree = None
		
	def getItem(self,item_id):
		self.item_id=item_id
		try:
			self.tree = parseString( self._getXml() )
		except:
			raise ItemNotParseable()
		
		data = {}
		try:
			error = self._getNode("error",0,0)
		except:
			pass
			
		if error:
			raise ItemNotFountException()
		
		data["name"] = self._getNode("name",0,0)
		data["level"] = self._getNode("level",0,0)
		data["quality"] = self._getNode("quality",0,0)
		data["quality_id"] = self._getAttribute("quality",0,"id")
		data["itemClass"] = self._getNode("class",0,0)
		data["class_id"] = self._getAttribute("class",0,"id")
		data["subclass"] = self._getNode("subclass",0,0)
		data["subclass_id"] = self._getAttribute("subclass",0,"id")
		data["icon"] = self._getNode("icon",0,0)
		data["icon_id"] = self._getAttribute("icon",0,"displayId")
		data["inventorySlot"] = self._getNode("inventorySlot",0,0)
		data["inventorySlot_id"] = self._getAttribute("inventorySlot",0,"id")
		data["htmlTooltip"] = self._getNode("htmlTooltip",0,0)
		data["json"] = self._getNode("json",0,0)
		data["jsonEquip"] = self._getNode("jsonEquip",0,0)
		data["link"] = self._getNode("link",0,0)
		return data
	
	def _getXml(self):
		strFile = ""
		try:
			url = "http://"+self.language.lower()+".wowhead.com/?item="+str(self.item_id)+"&xml"
			values = {}
			headers = { 'User-Agent' : self.userAgent }
			data = urllib.urlencode(values)
			socket.setdefaulttimeout(2)
			req = urllib2.Request(url, data, headers)
			response = urllib2.urlopen(req)
			strFile = response.read()
		except Exception, e:
			raise WowHeadConectionProblem()
		finally:
			return strFile
	
	def _getAttribute(self,node,number,attribute):
		try:
			return self.tree.getElementsByTagName(node)[number].getAttribute(attribute)
		except:
			return None
		
	def _getNode(self,node,number,child):
		try:
			return self.tree.getElementsByTagName(node)[number].childNodes[child].data
		except:
			return None